package com.tensuqare.user.config;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义拦截器用于签权
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //取得请求头Authorization
        String authorization = request.getHeader("Authorization");
        System.out.println("authorization1111 = " + authorization);
        //判断请求头是否以“bearer ”开头
        if(authorization!=null&&authorization.startsWith("Bearer ")){
            //取出token数据
            String token = authorization.substring(7);
            System.out.println("token1111111111 = " + token);
            //解析token数据
            Claims claims = jwtUtil.parseJWT(token);
            //判断token数据是否存在
            if(claims!=null){
                //获取角色信息
                String roles = (String) claims.get("roles");
                System.out.println("roles = " + roles);
                //判断是admin
                if(roles.equals("admin")){
                    request.setAttribute("admin",claims);
                }
                //判断是user
                if(roles.equals("user")){
                    request.setAttribute("user",claims);
                }
            }
        }
        return true;
    }
}
